/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mail.account;

import java.io.File;
import java.util.*;
import mail.general.FileUtils;
import mail.general.FileUtils.FileBlock;
import mail.server.MailServer;

/**
 * 
 * @author Ernesto Soto Roca
 * @author timoteo
 */
public class FileUserDatabase implements UserDatabase {

    public static final String CONFIG_FILE = MailServer.DEFAULT_FOLDER + "/mail.config";
    private String fileLocation;

    public FileUserDatabase(String fileLocation) {
        this.fileLocation = fileLocation;
    }

    public FileUserDatabase() {
        this(CONFIG_FILE);
    }

    @Override
    public Boolean userExists(final String user) {
        if (!FileUtils.fileExists(fileLocation)) {
            return false;
        }
        final StringBuilder occurrences = new StringBuilder();
        FileUtils.readFile(fileLocation, new FileBlock() {

            @Override
            public void processLine(String line) {
                if (line.equals(user)) {
                    occurrences.append(line);
                }
            }
        });
        return occurrences.toString().length() > 0;
    }

    @Override
    public List<UserAccount> getUserList() {
        final List<UserAccount> accountsList = new ArrayList<UserAccount>();
        if (FileUtils.fileExists(fileLocation)) {
            FileUtils.readFile(fileLocation, new FileBlock() {

                @Override
                public void processLine(String line) {
                    UserAccount user = new UserAccount(line);
                    accountsList.add(user);
                }
            });
        }
        return accountsList;
    }

    @Override
    public void add(UserAccount userAccount) {
        String username = userAccount.toString();
        FileUtils.appendToFile(fileLocation,"\n"+username);
        FileUtils.createFolder(MailServer.DEFAULT_FOLDER+"/"+username);
    }
}
